<?php
namespace App\Http\Controllers;
use App\AdminUser;
use Illuminate\Support\Facades\DB;


class AddressBookController extends Controller{
    public function setting(AdminUser $adminUser){
        return view('admin.test.user',compact('adminUser'));
    }


    /**
     * 展示通讯录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        return view('admin.AddressBook.index');
//        $users=[];
//        for($i=1;$i<10;$i++)
//        {
//            $users['name']='test'+$i;
//            $users['password']="123456";
//            $users['address']='地址测试'+"'"+$i+"'"+"11";
//            $users['phone']='231321'+"'"+$i+"'";
//            $users['email']='521321'+$i;
//            AdminUser::create($users); //创建字段
//        }
        //print_r($users);die;



    }
    /**
     * 数据接口
     */
    public function data()
    {
        //dd(AdminUser::with('roles')->get());

    }
    /**
     * 添加界面
     */
    public function create(){
        return view('admin.AddressBook.userInfo');
    }
    public function showMsg($status,$message = '',$data = array()){

        $result = array(
            'status' => $status,
            'message' =>$message,
            'data' =>$data
        );
        exit( json_encode($result));
    }
    public function upload(){

        if ($_FILES) {
            //上传图片具体操作
            $file_name = $_FILES['file']['name'];
            //$file_type = $_FILES["file"]["type"];
            $file_tmp = $_FILES["file"]["tmp_name"];
            $file_error = $_FILES["file"]["error"];
            $file_size = $_FILES["file"]["size"];

            if ($file_error > 0) { // 出错
                $message = $file_error;
            } elseif($file_size > 1048576) { // 文件太大了
                $message = "上传文件不能大于1MB";
            }else{
                $date = date('Ymd');
                $file_name_arr = explode('.', $file_name);
                $new_file_name = date('YmdHis') . '.' . $file_name_arr[1];

                $path = base_path()."/public/upload/".$date."/";
                $file_path = $path . $new_file_name;

                if (file_exists($file_path)) {
                    $message = "此文件已经存在啦";
                } else {
                    //TODO 判断当前的目录是否存在，若不存在就新建一个!
                    if (!is_dir($path)){
                        mkdir($path,0777);
                    }
                    $upload_result = move_uploaded_file($file_tmp, $file_path);
                    //此函数只支持 HTTP POST 上传的文件
                    if ($upload_result) {
                        $status = 1;
                        $message = $file_path;
                        $return_file="/upload/".$date."/".$new_file_name;
                    } else {
                        $message = "文件上传失败，请稍后再尝试";
                        $return_file="文件上传失败，请稍后再尝试";
                    }
                }
            }
        } else {
            $message = "参数错误";
        }

        return $this->showMsg($status, $return_file);
    }

    /**
     * 构建一个数组
     * @param array ...$numbers 参数
     */
    public function filds(...$numbers){
        $filds=array();
        if($_REQUEST && is_array($_REQUEST)){   //组成一个我所要的数组用于数据库更新
            //print_r($_REQUEST);die;
            foreach($numbers as $fild){
                foreach ($_REQUEST as $key=> $value){
                    if($fild==$key)
                    {
                        if($key=='password')
                        {
                            $filds[$fild]=bcrypt($value);
                        }
                        $filds[$fild] = $value;
                        continue;
                    }
                }
            }
        }
        return $filds;
    }

    /**
     * 添加操作逻辑简单实现
     */
    public function store(){
        //dd($_REQUEST);
        $param=$this->filds('name','password','user_name','gender','phone','address','email','introduction','image');
        $prov=$_REQUEST['prov'];//省
        $city=$_REQUEST['city'];//市
        $dist=$_REQUEST['dist'];//区
        $address=$prov.'_'.$city.'_'.$dist;//地址
        $param['address']=$address;
        $aihao="";
        $n=1;
        foreach($_REQUEST['like1'] as $item)
        {
            if($n!=count($_REQUEST['like1'])) {
                $n = $n + 1;
                $aihao = $aihao . $item . ',';
            }
        }
        $param['aihao']=$aihao;
        //print_r($param);die;
        $param["password"]=bcrypt($param["password"]);
        AdminUser::create($param); //创建字段
        //渲染
        return redirect("/admin/user");
    }
    /*
     * 删除单个
     */
    public function delete($id)
    {
        AdminUser::where('id', '=', $id)->delete();
        return back();
    }
    ///备用批量删除手法
    public function DeleteAll($data){
        switch(count($data))
        {
            case 1:AdminUser::whereIn('id',[$data[0]])->delete();break;
            case 2:AdminUser::whereIn('id',[$data[0],$data[1]])->delete();break;
            case 3:AdminUser::whereIn('id',[$data[0],$data[1],$data[2]])->delete();break;
            case 4:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3]])->delete();break;
            case 5:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4]])->delete();break;
            case 6:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5]])->delete();break;
            case 7:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6]])->delete();break;
            case 8:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7]])->delete();break;
            case 9:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7],$data[8]])->delete();break;
            case 10:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7],$data[8],$data[9]])->delete();break;
        }
    }
    //删除选中
    public function del(){
        $sql="delete from admin_users where";
        $column="";
        for($i=0;$i<count($_REQUEST);$i++)
        {
            if($i==(count($_REQUEST)-1)){
                $column=$column."id=".$_REQUEST[$i];
            }else{
                $column=$column."id=".$_REQUEST[$i]." "."or"." ";
            }
        }
        $sql=$sql." ".$column;
        if(DB::select($sql)){
            return -1;
        }
        else {
            return 1;
        }

        //return


       // $this->DeleteAll( $_REQUEST); //另类删除手法

        //AdminUser::whereIn('id',$bb)->get();

        ///AdminUser::where
    }
    public function update(){
        //print_r(json_decode($_REQUEST),true)
        //$data=json_decode($_REQUEST,true);
      $filds=$this->array_hebing('name','user_name','address','phone','email','gender');//传入需要更新的字段

      if(empty($filds))  //判断数据是否为空 是则不修改
      {
          return ['statu'=>'0'];
      }
      else{
          AdminUser::where('id', $_REQUEST['id'])->update($filds);
          return ['statu'=>'200'];
      }

    }

    //修改密码界面
    public function Edit_password(){
        $users=AdminUser::get();

        return view('admin.AddressBook.pwd_update',compact('users'));
    }
    public function edit(AdminUser $Admin_user){
        $users=$Admin_user;
//        if($users->aihao!=null)
//        {
//            $aihao=explode(",",$users->aihao);
//        }
        return view('admin.AddressBook.update',compact('users'));
    }
    public function edit_view(AdminUser $adminUser)
    {
        $prov=$_REQUEST['prov'];//省
        $city=$_REQUEST['city'];//市
        $dist=$_REQUEST['dist'];//区
        $aihao="";
        if(isset($_REQUEST['like1'])) {
            foreach ($_REQUEST['like1'] as $item) {
                $aihao = $aihao . $item . ',';
            }
            $adminUser->aihao=$aihao;
        }
        $address=$prov.'_'.$city.'_'.$dist;//地址
        $adminUser->name=request('name');
        $adminUser->user_name=request('user_name');
        $adminUser->address=$address;
        $adminUser->phone=request('phone');
        $adminUser->email=request('email');
        $adminUser->gender=request('gender');
        $adminUser->image=request('image');
        $adminUser->introduction=request('introduction');
        $adminUser->save();
        //return redirect('/admin/user');
        return  '<script type="text/javascript">window.parent.location.reload()</script>';
    }
    //修改密码逻辑
    public function store_password(){
        $option=$_REQUEST['option'];// -1未选1择 0=批量修改 1=单独修改
        if($_REQUEST['password_1']==$_REQUEST['password_2'])
        {
            $is_true=true;
        }
        else {
            return  '<script type="text/javascript">alert("2次密码不同");window.parent.location.reload();</script>';
        }
        if($option==-1 || $is_true)
        {
            return  '<script type="text/javascript">window.parent.location.reload()</script>';
        }
        else if($option==0 && $is_true){
            $sql="update admin_users set password='".(bcrypt($_REQUEST['password_1']))."' where";
            $column="";
            $arr=$_REQUEST['lists'];
            for($i=0;$i<count($arr);$i++)
            {
                if($i==(count($arr)-1)){
                    $column=$column."id=".$arr[$i];
                }else{
                    $column=$column."id=".$arr[$i]." "."or"." ";
                }
            }
            $sql=$sql." ".$column;
            //dd($sql);
            if(DB::select($sql)>0){
                return redirect("/admin/user");
            }
        }else if($option==1 && $is_true){
             DB::table('admin_users')->where('id',$_REQUEST['user_id'])->update(['password'=>bcrypt($_REQUEST['password_1']) ]);
            return  '<script type="text/javascript">window.parent.location.reload()</script>';
        }

    }
    public function Edit_pwd(){
        return view('admin/AddressBook/pwd_edit');
    }
    public function store_pwd(AdminUser $adminUser){
        if(encrypt($adminUser->password)!=$_REQUEST['password'])
        {
             return "<script> alert('密码错误'); window.history.back();</script>";
        }
        else {
            if($_REQUEST['password1']==$_REQUEST['password2']){
                $adminUser->password=bcrypt($_REQUEST['password2']);
                $adminUser->save();
                return redirect('admin/home');
            }else{
                return "<script> alert('两次密码出错');window.history.back();</script>";
            }
        }


    }
    /**
     * //组成一个我所要的数组用于数据库更新 并且
     * @param array ...$numbers 传进去的字段
     * @return array /￥/返回一个键=字段 值=数值的数组
     */
    public function array_hebing(...$numbers){
        $data=AdminUser::where('id', $_REQUEST['id'])->first();;
        $filds=[];
        if($_REQUEST && is_array($_REQUEST)){   //组成一个我所要的数组用于数据库更新
            //print_r($_REQUEST);die;
            foreach($numbers as $fild){
                foreach ($_REQUEST as $key=> $value){
                    if($fild==$key)
                    {
                            $filds[$fild] = $value;
                            continue;
                    }
                }
            }
            $start=0;  //循环记数
            foreach($filds as $key=>$value)  //删除请求更新字段中没有修改的字段
            {
                if($data[$key]==$filds[$key]) {   //判断是否相同 相同则从需要更新的数组中删除该键值
                        array_splice($filds, $start, 1);//删除该字段
                        $start=$start-1;
                }
                $start=$start+1;
            }
        }
        return $filds;
    }
    //用户角色页面
    public function role(\App\AdminUser $user){

        $roles=\App\AdminRole::all();
        $myRoles=$user->roles;
        return view('/admin/role/role',compact('roles','myRoles','user'));
    }
    //存储用户角色
    public function storeRole(\App\AdminUser $user){
        $this->validate(request(),[
            'roles'=>'required|array'
        ]);
        $roles=\App\AdminRole::findMany(request('roles'));
        $myRoles=$user->roles;
        //要增加的
        $addRoles=$roles->diff($myRoles);
        foreach($addRoles as $role){
            $user->assignRole($role);
        }

        //要删除的
        $deleteRoles=$myRoles->diff($roles);
        foreach($deleteRoles as $role){
            $user->deleteRole($role);
        }
        return redirect('/admin/user');

    }
}